<template>
    <div>
        <a-form>
            <a-form-item>
                <img :src="uploadAvatarImage" style="height: 60px; width: 60px;" alt="" v-if="uploadAvatarImage">
                <!-- <img :src="formData.image" style="height: 60px; width: 60px;" alt="" v-else> -->
                <a-upload class="upload" v-model:file-list="fileList" name="file" v-else action="" :headers="headers"
                    :before-upload="beforeUpload" :customRequest="uploadImage" @change="handleChange">
                    <a-button>
                        <upload-outlined></upload-outlined>
                        上传图片
                    </a-button>
                </a-upload>
            </a-form-item>
        </a-form>
    </div>
</template>

<script setup lang='ts'>
import type { UploadChangeParam, UploadProps } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'

const emit = defineEmits<{
    (e: 'uploadSuccess', imageUrl: string): void,
    (e: 'uploadUrl', imageUrl: string): void,
}>()

const uploadAvatarImage = ref<string>('')
const formData = reactive({
    image: ''
})
// 头像上传
const handleChange = (info: UploadChangeParam) => {
    if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
        // uploadAvatarImage.value = info.file.response.data.url
        // formData.image = uploadAvatarImage.value
    }
    if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
    }
};
const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};
const uploadImage =async (params: any) => {
    console.log(params.file)
    const res = await upload(params.file)
   
    if (res.code === 201 && res.data.url) {
            // 拿到了腾讯云返回的地址
            // 通过input自定义事件将地址传出去
            emit('uploadUrl', res.data.url) // 将地址返回了
            uploadAvatarImage.value = res.data.url
            formData.image = res.data.url
            message.success(`${params.file.name} file uploaded successfully`);
        } else {
            message.error(`${params.file.name} file upload failed.`);
        }
}

const fileList = ref([]);
const headers = reactive({
    authorization: 'authorization-text',
})

watch(() => formData.image, (newValue) => {
    // console.log('formData改变了', newValue)
    emit('uploadSuccess', newValue)
})
</script>

<style scoped></style>